package com.bestcem.xm.deliver.grpc.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bestcem.bp.xm.user.grpc.v1.services.GroupNode;
import com.bestcem.xm.common.core.oss.enums.OssPathEnum;
import com.bestcem.xm.common.core.uitls.SignUtil;
import com.bestcem.xm.componet.redis.service.RedisService;
import com.bestcem.xm.deliver.entity.*;
import com.bestcem.xm.deliver.enums.DeliverChannelEnum;
import com.bestcem.xm.deliver.enums.DeliverTtypeEnum;
import com.bestcem.xm.deliver.grpc.client.UserGrpcClient;
import com.bestcem.xm.deliver.grpc.client.dto.OrgInfoDto;
import com.bestcem.xm.deliver.grpc.v1.services.*;
import com.bestcem.xm.deliver.mapper.*;
import com.bestcem.xm.deliver.mq.dto.StatusDto;
import com.bestcem.xm.deliver.mq.send.biz.DeliverMessageSendService;
import com.bestcem.xm.deliver.service.DeliverDeliverService;
import com.bestcem.xm.deliver.service.ServiceSequenceService;
import com.bestcem.xm.deliver.util.CommonUtil;
import io.grpc.stub.StreamObserver;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import zhongyan.xm.base.v1.Base;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

import static com.bestcem.xm.deliver.enums.DeliverChannelEnum.DELIVER_CHANNEL_QRCODE;
import static com.bestcem.xm.deliver.enums.DeliverScenesEnum.DELIVER_SCENES_CONSUMER;
import static com.bestcem.xm.deliver.enums.DeliverScenesEnum.DELIVER_SCENES_QRCODE;
import static com.bestcem.xm.deliver.enums.DeliverStatusEnum.*;
import static com.bestcem.xm.deliver.enums.DeliverTtypeEnum.*;
import static com.bestcem.xm.deliver.grpc.v1.services.DefaultDeliverStatus.DEFAULTDELIVER_STATUS_ACTIVATE;
import static com.bestcem.xm.deliver.grpc.v1.services.DefaultDeliverStoreStatus.DEFAULTDELIVERSTORE_STATUS_ACTIVATE_VALUE;
import static com.bestcem.xm.deliver.grpc.v1.services.DefaultDeliverStoreStatus.DEFAULTDELIVERSTORE_STATUS_DISACTIVATE_VALUE;
import static com.bestcem.xm.deliver.grpc.v1.services.DefaultDeliverStoreTtype.DEFAULTDELIVERSTORE_TTYPE_STORE;
import static com.bestcem.xm.deliver.grpc.v1.services.DeliverAwardUseType.DELIVER_AWARD_USE_TYPE_UNUSE;
import static com.bestcem.xm.deliver.grpc.v1.services.DeliverAwardUseType.DELIVER_AWARD_USE_TYPE_USE;
import static com.bestcem.xm.deliver.grpc.v1.services.DeliverDelayFailedTtype.DELIVER_DELAY_FAILED_TTYPE_CONSOLE;
import static com.bestcem.xm.deliver.grpc.v1.services.SurveyRegionTtype.SURVEYREGION_TTYPE_GLOBAL;
import static com.bestcem.xm.deliver.grpc.v1.services.WechatDeliverGtype.WECHATDELIVER_GTYPE_NULL;
import static com.bestcem.xm.deliver.grpc.v1.services.WechatDeliverTtype.WECHATDELIVER_TTYPE_NODELAY;

@GrpcService
@Slf4j
@RequiredArgsConstructor
public class BpDeliverGrpcService extends BpDeliverServiceGrpc.BpDeliverServiceImplBase {

    private static final Base.Status SUCCESS_STATUS = Base.Status.newBuilder().setCode(Base.Code.OK).build();
    private static final Base.Status FAIL_STATUS = Base.Status.newBuilder().setCode(Base.Code.ERROR).build();

    private static final String SEPARATOR = "/";
    private static final String ROOT_FILE_PATH = System.getProperty("user.dir");

    private @NonNull com.bestcem.xm.deliver.convert.grpc.DeliverGrpcConvertMapper deliverGrpcConvertMapper;
    private @NonNull UserGrpcClient userGrpcClient;

    private @NonNull DeliverDeliverService deliverDeliverService;
    private @NonNull ServiceSequenceService serviceSequenceService;
    private @NonNull RedisService redisService;
    private @NonNull DeliverMessageSendService deliverMessageSendService;

    private @NonNull DeliverDedicatedDeliverMapper deliverDedicatedDeliverMapper;
    private @NonNull DeliverDefaultDeliverMapper deliverDefaultDeliverMapper;
    private @NonNull DeliverDeliverMapper deliverDeliverMapper;
    private @NonNull DeliverDefaultDeliverStoreMapper deliverDefaultDeliverStoreMapper;
    private @NonNull DeliverWechatDeliverMapper wechatDeliverMapper;
    private @NonNull DeliverSurveyDeliverMapper deliverSurveyDeliverMapper;
    private @NonNull DeliverDisturbRuleMapper deliverDisturbRuleMapper;

    private Boolean getDedicatedDeliverDelete(String deliver_id, String code) {
        DeliverDedicatedDeliver dedicated_deliver = deliverDedicatedDeliverMapper.selectOne(
                new QueryWrapper<DeliverDedicatedDeliver>().lambda()
                        .eq(DeliverDedicatedDeliver::getDeliverId, deliver_id)
                        .eq(DeliverDedicatedDeliver::getCode, code)
        );

        return dedicated_deliver.getDeleted();
    }

    private Integer getDefaultDeliverDisable(String deliver_id) {
        DeliverDefaultDeliver default_deliver = deliverDefaultDeliverMapper.selectOne(
                new QueryWrapper<DeliverDefaultDeliver>().lambda()
                        .eq(DeliverDefaultDeliver::getDeliverId, deliver_id)
                        .eq(DeliverDefaultDeliver::getTtype, 0)
        );
        /*if (ObjectUtils.isEmpty(default_deliver)) {
            return 0;
        } else {
            return default_deliver.getDisable();
        }*/
        return ObjectUtils.isEmpty(default_deliver) ? 0 : default_deliver.getDisable();
    }

    private JSONObject getDefaultDeliverStoreDisable(String deliver_id, String code) {
        DeliverDefaultDeliverStore default_deliver_store = deliverDefaultDeliverStoreMapper.selectOne(
                new QueryWrapper<DeliverDefaultDeliverStore>().lambda()
                        .eq(DeliverDefaultDeliverStore::getDeliverId, deliver_id)
                        .eq(DeliverDefaultDeliverStore::getCode, code)
                        .eq(DeliverDefaultDeliverStore::getStatus, DEFAULTDELIVERSTORE_STATUS_ACTIVATE_VALUE)
        );
        JSONObject result = new JSONObject();
        if (Objects.nonNull(default_deliver_store)) {
            result.put("disable", default_deliver_store.getDisable());
            result.put("status", default_deliver_store.getStatus());
        } else {
            default_deliver_store = deliverDefaultDeliverStoreMapper.selectOne(
                    new QueryWrapper<DeliverDefaultDeliverStore>().lambda()
                            .eq(DeliverDefaultDeliverStore::getDeliverId, deliver_id)
                            .eq(DeliverDefaultDeliverStore::getCode, code)
                            .eq(DeliverDefaultDeliverStore::getStatus, DEFAULTDELIVERSTORE_STATUS_DISACTIVATE_VALUE)
            );
            if (Objects.nonNull(default_deliver_store)) {
                result.put("disable", 0);
                result.put("status", default_deliver_store.getStatus());
            } else {
                result.put("disable", 0);
                result.put("status", 0);
            }
        }
        return result;
    }

    @Override
    public void getQrDeliverDisable(GetQrDeliverDisableRequest request, StreamObserver<GetQrDeliverDisableResponse> responseObserver) {
        GetQrDeliverDisableResponse.Builder result = GetQrDeliverDisableResponse.newBuilder();
        String deliver_id = request.getDeliverId();
        String code = request.getCode();
        Integer disable;
        Integer status;
        try {
            if (StrUtil.isEmptyIfStr(code)) {
                disable = getDefaultDeliverDisable(deliver_id);
                status = 0;
            } else {
                JSONObject temp = getDefaultDeliverStoreDisable(deliver_id, code);
                disable = temp.getInteger("disable");
                status = temp.getInteger("status");
            }

            GetQrDeliverDisableObject.Builder obj = GetQrDeliverDisableObject.newBuilder();
            obj.setStatus(status);
            obj.setDisable(disable);

            result.setStatus(SUCCESS_STATUS);
            result.setResultObj(obj);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            log.error("getQrDeliverDisable service error", e);
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getDedicatedDeliverDel(GetDedicatedDeliverDelRequest request, StreamObserver<GetDedicatedDeliverDelResponse> responseObserver) {
        GetDedicatedDeliverDelResponse.Builder result = GetDedicatedDeliverDelResponse.newBuilder();
        try {

            String deliver_id = request.getDeliverId();
            String ded_code = request.getDedCode();

            result.setStatus(SUCCESS_STATUS);
            result.setIsDeleted(getDedicatedDeliverDelete(deliver_id, ded_code));
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            log.error("getDedicatedDeliverDel service error", e);
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getWxShareQrcodeImgurl(GetWxShareQrcodeImgurlRequest request, StreamObserver<GetWxShareQrcodeImgurlResponse> responseObserver) {
        GetWxShareQrcodeImgurlResponse.Builder result = GetWxShareQrcodeImgurlResponse.newBuilder();
        String orgId = request.getOrgId();
        String surveyId = request.getSurveyId();
        String deliverId = request.getDeliverId();
        String orgCode = request.getOrgCode();
        Map<String, String> unmodifiableMap = request.getKwargsMap();
        Map<String, String> kwargs = new HashMap<>(unmodifiableMap);
        log.info("getWxShareQrcodeImgurl server orgCode=" + orgCode);
        try {
            JSONObject surveyLink = deliverDeliverService.getSurveyLink(orgId, surveyId, deliverId, orgCode, kwargs);
            String url = surveyLink.getString("url");
            //长链转短链
            String share_url = deliverDeliverService.getSurveyDwzLink(url, null);

            // 生成二维码
            String fileName = "通用微信.png";
            String tmpPath = ROOT_FILE_PATH + File.separator + "temp" + File.separator;
            String ossPath = OssPathEnum.QRCODE.getPath() + surveyId + SEPARATOR + deliverId;
            String wxshare_qrcode_img = deliverDeliverService.saveMatrixImgByParam(share_url, tmpPath, ossPath, fileName, false);

            result.setStatus(SUCCESS_STATUS);
            result.setWxshareQrcodeImg(wxshare_qrcode_img);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            log.error("getWxShareQrcodeImgurl service error ", e);
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        }
    }

    @Override
    public void createWechatdeliverWithName(CreateWechatdeliverWithNameRequest request, StreamObserver<CreateWechatdeliverWithNameResponse> responseObserver) {
        CreateWechatdeliverWithNameResponse.Builder result = CreateWechatdeliverWithNameResponse.newBuilder();

        try {
            DeliverDeliver deliver = new DeliverDeliver();
            deliver.setOrgId(request.getOrgId());
            deliver.setCreatedId(request.getUserId());
            deliver.setName(request.getName());
            deliver.setTtype(DeliverTtypeEnum.DELIVER_TTYPE_WECHAT.getValue());
            deliver.setChannel(DeliverChannelEnum.DELIVER_CHANNEL_WECHAT.getValue());
            deliver.setScenes(DELIVER_SCENES_CONSUMER.getValue());
            deliver.setStatus(DELIVER_STATUS_STOP.getValue());
            deliver.setStarttime(LocalDateTime.now());
            Integer code = serviceSequenceService.getSequence("DELIVER", 1);
            deliver.setCode(String.valueOf(code));
            //默认值
            deliver.setDisable(0);
            deliver.setDelayTime("[]");
            deliver.setDelayFailedTime("{}");
            deliver.setAwardUseType(DELIVER_AWARD_USE_TYPE_UNUSE.getNumber());
            deliver.setEnableRespondent(1);
            deliverDeliverMapper.insert(deliver);

            setDeliverRespondentEnableRedis(deliver.getId(), true);

            DeliverSurveyDeliver surveyDeliver = new DeliverSurveyDeliver();
            surveyDeliver.setCreatedId(request.getUserId());
            surveyDeliver.setOrgId(request.getOrgId());
            surveyDeliver.setDeliverId(deliver.getId());
            surveyDeliver.setSurveyId(request.getSurveyId());
            deliverSurveyDeliverMapper.insert(surveyDeliver);

            //await redis_mq.publish(topics.project_updated, {'project_id': params.get("survey_id")})
            StatusDto dto = new StatusDto();
            dto.setProjectId(request.getSurveyId());
            deliverMessageSendService.projectUpdated(dto);

            Map<String, Object> signMap = new HashMap<>();
            signMap.put("group_id_list", "[]");
            signMap.put("ttype", WECHATDELIVER_TTYPE_NODELAY.getNumber());
            signMap.put("delay_time", "{}");
            signMap.put("deliver_delay_time", "[]");
            signMap.put("deliver_delay_failed_ttype", DELIVER_DELAY_FAILED_TTYPE_CONSOLE.getNumber());
            signMap.put("deliver_delay_failed_time", "{}");
            String hashcode = SignUtil.genSign(signMap, deliverDeliverService.getDeliverSecret());

            DeliverWechatDeliver wechatDeliver = new DeliverWechatDeliver();
            wechatDeliver.setOrgId(request.getOrgId());
            wechatDeliver.setSurveyId(request.getSurveyId());
            wechatDeliver.setDeliverId(deliver.getId());
            wechatDeliver.setHashcode(hashcode);
            //默认值
            wechatDeliver.setTemplate("{}");
            wechatDeliver.setGroupIdList("[]");
            wechatDeliver.setGtype(WECHATDELIVER_GTYPE_NULL.getNumber());
            wechatDeliver.setTtype(WECHATDELIVER_TTYPE_NODELAY.getNumber());
            wechatDeliver.setDelayTime("{}");
            wechatDeliver.setNoDisturbMemberIdList("[]");
            wechatDeliverMapper.insert(wechatDeliver);

            //微信、阿里被动投放合并为事件投放，默认投放序号设置为 DELIVER_TTYPE_ALIPAY
            deliverDeliverService.doDefaultDeliverNameSeq(deliver.getName(), request.getSurveyId(), DELIVER_TTYPE_ALIPAY.getValue());

            result.setStatus(SUCCESS_STATUS);
            result.setDeliverId(deliver.getId());
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            log.error("createWechatdeliverWithName service error", e);
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
        }
    }

    @Override
    public void queryWechatDeliverByParam(QueryWechatDeliverRequest request, StreamObserver<QueryWechatDeliverResponse> responseObserver) {
        QueryWechatDeliverResponse.Builder result = QueryWechatDeliverResponse.newBuilder();
        LambdaQueryWrapper<DeliverWechatDeliver> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(request.getId()), DeliverWechatDeliver::getId, request.getId())
                .eq(StrUtil.isNotBlank(request.getOrgId()), DeliverWechatDeliver::getOrgId, request.getOrgId())
                .eq(StrUtil.isNotBlank(request.getDeliverId()), DeliverWechatDeliver::getDeliverId, request.getDeliverId())
                .eq(StrUtil.isNotBlank(request.getSurveyId()), DeliverWechatDeliver::getSurveyId, request.getSurveyId());
        DeliverWechatDeliver deliverWechat = wechatDeliverMapper.selectOne(wrapper);

        if (ObjectUtils.isEmpty(deliverWechat)) {
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }

        result.setStatus(SUCCESS_STATUS);
        result.setWechatDeliverInfo(deliverGrpcConvertMapper.toGrpcWechatDeliverInfo(deliverWechat));
        responseObserver.onNext(result.build());
        responseObserver.onCompleted();
    }

    @Override
    public void checkOrgHasUnfinishDeliver(CheckOrgHasUnfinishDeliverRequest request, StreamObserver<CheckOrgHasUnfinishDeliverResponse> responseObserver) {
        CheckOrgHasUnfinishDeliverResponse.Builder result = CheckOrgHasUnfinishDeliverResponse.newBuilder();
        String orgId = request.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }
        LambdaQueryWrapper<DeliverDeliver> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeliverDeliver::getOrgId, orgId);
        wrapper.in(DeliverDeliver::getTtype, Arrays.asList(DELIVER_TTYPE_SMS.getValue(), DELIVER_TTYPE_EMAIL.getValue()));
        List<DeliverDeliver> delivers = deliverDeliverMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(delivers)) {
            List<Integer> status = Arrays.asList(DELIVER_STATUS_FINISH.getValue(), DELIVER_STATUS_DELETE.getValue(),
                    DELIVER_STATUS_DONE.getValue(), DELIVER_STATUS_FINISH_STOP.getValue());
            for (DeliverDeliver deliver : delivers) {
                if (!status.contains(deliver.getStatus())) {
                    // 有投放尚未完成，不能设置审核属性
                    result.setStatus(SUCCESS_STATUS);
                    result.setPassed(false);
                    responseObserver.onNext(result.build());
                    responseObserver.onCompleted();
                    return;
                }
            }
        }
        result.setPassed(true);
        result.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(result.build());
        responseObserver.onCompleted();
    }

    @Override
    public void checkAwardUsed(CheckAwardUsedRequest request, StreamObserver<CheckAwardUsedResponse> responseObserver) {
        CheckAwardUsedResponse.Builder result = CheckAwardUsedResponse.newBuilder();
        String awardId = request.getId();
        if (StringUtils.isEmpty(awardId)) {
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }
        LambdaQueryWrapper<DeliverDeliver> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeliverDeliver::getAwardId, awardId);
        List<DeliverDeliver> delivers = deliverDeliverMapper.selectList(wrapper);
        boolean use = false;
        if (CollectionUtils.isEmpty(delivers)) {
            result.setStatus(SUCCESS_STATUS);
            result.setUse(use);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }
        for (DeliverDeliver deliver : delivers) {
            if (deliver.getStatus() != DELIVER_STATUS_DELETE.getValue()) {
                use = true;
                break;
            }
        }
        result.setStatus(SUCCESS_STATUS);
        result.setUse(use);
        responseObserver.onNext(result.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getDeliverInfo(GetDeliverInfoRequest request, StreamObserver<GetDeliverInfoResponse> responseObserver) {
        GetDeliverInfoResponse.Builder result = GetDeliverInfoResponse.newBuilder();
        String id = request.getId();
        if (StringUtils.isEmpty(id)) {
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }
        DeliverDeliver deliver = deliverDeliverMapper.selectById(id);
        if (deliver == null) {
            result.setStatus(Base.Status.newBuilder().setCode(Base.Code.ERROR).setMessage("Deliver not found").build());
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }
        DeliverInfo.Builder builder = DeliverInfo.newBuilder();
        if (StringUtils.isNotEmpty(deliver.getName())) {
            builder.setName(deliver.getName());
        }
        if (deliver.getChannel() != null) {
            builder.setSourceValue(deliver.getChannel());
        }
        if (StringUtils.isNotEmpty(deliver.getAwardId())) {
            builder.setAwardId(deliver.getAwardId());
        }
        result.setDeliver(builder.build());
        result.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(result.build());
        responseObserver.onCompleted();
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public void addDefaultDeliverBase(AddDefaultDeliverBaseRequest request,
                                      StreamObserver<AddDefaultDeliverBaseResponse> responseObserver) {
        String projectId = request.getProjectId();
        String userId = request.getUserId();
        String orgId = request.getOrgId();
        log.info("创建默认 通用二维码/链接投放 survey_id=={}, user_id={}", projectId, userId);
        AddDefaultDeliverBaseResponse.Builder result = AddDefaultDeliverBaseResponse.newBuilder();
        if (StringUtils.isEmpty(projectId)) {
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }
        DeliverDeliver deliver = new DeliverDeliver();
        deliver.setOrgId(orgId);
        deliver.setCreatedId(userId);
        deliver.setName("通用二维码/链接投放");
        deliver.setReason("survey_region_deliver:" + projectId + ":default");
        deliver.setTtype(DELIVER_TTYPE_DEFAULT.getValue());
        deliver.setChannel(DELIVER_CHANNEL_QRCODE.getValue());
        deliver.setScenes(DELIVER_SCENES_QRCODE.getValue());
        deliver.setStatus(DELIVER_STATUS_START.getValue());
        deliver.setStarttime(LocalDateTime.now());
        deliver.setCode(String.valueOf(serviceSequenceService.getSequence("DELIVER", 1)));
        deliver.setAwardUseType(DELIVER_AWARD_USE_TYPE_UNUSE.getNumber());
        // 设置默认值
        deliver.setDisable(0);
        deliver.setDelayTime("[]");
        deliver.setDelayFailedTime("{}");
        deliver.setEnableRespondent(1);
        deliverDeliverMapper.insert(deliver);
        setDeliverRespondentEnableRedis(deliver.getId(), true);

        DeliverSurveyDeliver surveyDeliver = new DeliverSurveyDeliver();
        surveyDeliver.setCreatedId(userId);
        surveyDeliver.setOrgId(orgId);
        surveyDeliver.setDeliverId(deliver.getId());
        surveyDeliver.setSurveyId(projectId);
        deliverSurveyDeliverMapper.insert(surveyDeliver);

        // 创建
        createDefaultBase(orgId, deliver, projectId);
        deliverDeliverService.doDefaultDeliverNameSeq(deliver.getName(), projectId, DELIVER_TTYPE_DEFAULT_STORE.getValue());

        result.setStatus(SUCCESS_STATUS);
        result.setId(deliver.getId());
        responseObserver.onNext(result.build());
        responseObserver.onCompleted();
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public void addDefaultDeliverStore(AddDefaultDeliverStoreRequest request,
                                       StreamObserver<AddDefaultDeliverStoreResponse> responseObserver) {
        String projectId = request.getProjectId();
        String userId = request.getUserId();
        String orgId = request.getOrgId();
        log.info("创建默认 组织连接 通用二维码/链接投放 survey_id=={}, user_id={}", projectId, userId);
        AddDefaultDeliverStoreResponse.Builder result = AddDefaultDeliverStoreResponse.newBuilder();
        if (StringUtils.isEmpty(projectId)) {
            result.setStatus(FAIL_STATUS);
            responseObserver.onNext(result.build());
            responseObserver.onCompleted();
            return;
        }
        DeliverDeliver deliver = new DeliverDeliver();
        deliver.setOrgId(orgId);
        deliver.setCreatedId(userId);
        deliver.setName("组织二维码/链接投放");
        deliver.setReason("survey_region_deliver:" + projectId + ":default");
        deliver.setTtype(DELIVER_TTYPE_DEFAULT_STORE.getValue());
        deliver.setChannel(DELIVER_CHANNEL_QRCODE.getValue());
        deliver.setScenes(DELIVER_SCENES_QRCODE.getValue());
        deliver.setStatus(DELIVER_STATUS_START.getValue());
        deliver.setStarttime(LocalDateTime.now());
        deliver.setCode(String.valueOf(serviceSequenceService.getSequence("DELIVER", 1)));
        deliver.setAwardUseType(DELIVER_AWARD_USE_TYPE_UNUSE.getNumber());
        // 设置默认值
        deliver.setDisable(0);
        deliver.setDelayTime("[]");
        deliver.setDelayFailedTime("{}");
        deliver.setEnableRespondent(1);
        deliverDeliverMapper.insert(deliver);
        setDeliverRespondentEnableRedis(deliver.getId(), true);

        DeliverSurveyDeliver surveyDeliver = new DeliverSurveyDeliver();
        surveyDeliver.setCreatedId(userId);
        surveyDeliver.setOrgId(orgId);
        surveyDeliver.setDeliverId(deliver.getId());
        surveyDeliver.setSurveyId(projectId);
        deliverSurveyDeliverMapper.insert(surveyDeliver);

        // 创建
        OrgInfoDto organization = userGrpcClient.getOrganization(orgId);
        String rootGroupId = organization.getRootGroupId();
        if (!StrUtil.isEmpty(rootGroupId)) {
            createDefaultList(orgId, deliver, projectId, rootGroupId);
        }
        deliverDeliverService.doDefaultDeliverNameSeq(deliver.getName(), projectId, DELIVER_TTYPE_DEFAULT_STORE.getValue());

        result.setStatus(SUCCESS_STATUS);
        result.setId(deliver.getId());
        responseObserver.onNext(result.build());
        responseObserver.onCompleted();
    }

    private void setDeliverRespondentEnableRedis(String deliverId, boolean enableRespondent) {
        // 设置是容许答题到redis中
        String key = "deliver:deliver_enable_respondent" + deliverId;
        // 创建投放时默认是容许答题
        // 设置redis 值为”1“ 容许答题 值为”0“ 不容许答题
        redisService.set(key, enableRespondent ? "1" : "0");
    }

    private void createDefaultBase(String orgId, DeliverDeliver deliver, String projectId) {
        Map<String, String> keyMap = new HashMap<>();
        if (deliver.getAwardUseType() == DELIVER_AWARD_USE_TYPE_USE.getNumber()) {
            keyMap.put("awardId", deliver.getAwardId());
        }
        String link = deliverDeliverService.getSurveyGroupDwzUrl(orgId, projectId, deliver.getId(), keyMap);
        // 创建对象时同步创建对应二维码
        deliverDeliverService.createSurveyGroupQrcodes(orgId, projectId, deliver.getId(), link, "通用.png", false);
        DeliverDefaultDeliver defaultDeliver = new DeliverDefaultDeliver();
        defaultDeliver.setOrgId(orgId);
        defaultDeliver.setDeliverId(deliver.getId());
        defaultDeliver.setSurveyId(projectId);
        defaultDeliver.setTtype(SURVEYREGION_TTYPE_GLOBAL.getNumber());
        defaultDeliver.setLink(link);
        defaultDeliver.setDisable(0);
        deliverDefaultDeliverMapper.insert(defaultDeliver);
    }

    private void createDefaultList(String orgId, DeliverDeliver deliver, String projectId, String rootGroupId) {
        Map<String, String> keyMap = new HashMap<>();
        if (deliver.getAwardUseType() == DELIVER_AWARD_USE_TYPE_USE.getNumber()) {
            keyMap.put("awardId", deliver.getAwardId());
        }
        GroupNode groupTree;
        JSONObject storeLevel = new JSONObject();
        if (StringUtils.isNotEmpty(rootGroupId)) {
            groupTree = userGrpcClient.getGroupTreeByRootGroupId(rootGroupId, false);
            List<JSONObject> levels = deliverDeliverService.getGroupLevel(rootGroupId);
            if (CollectionUtils.isNotEmpty(levels)) {
                storeLevel = levels.get(levels.size() - 1);
            }

            parseNode(orgId, groupTree, /*new ArrayList<>(),*/ storeLevel, keyMap, deliver, projectId, rootGroupId);
        }
    }

    private void parseNode(String orgId, GroupNode node, /*List<GroupNode> parentNodeList,*/ JSONObject storeLevel,
                           Map<String, String> keyMap, DeliverDeliver deliver, String projectId, String rootGroupId) {
       /* List<GroupNode> allNodeList = new ArrayList<>(parentNodeList);
        allNodeList.add(node);*/
        if (node.getLevelId().equals(storeLevel.getString("id"))) {
            int status = DEFAULTDELIVER_STATUS_ACTIVATE.getNumber();
            Map<String, String> newKeyMap = new HashMap<>();
            newKeyMap.put("code", node.getCode());
            if (keyMap.containsKey("awardId")) {
                newKeyMap.put("awardId", keyMap.get("awardId"));
            }
            String link = deliverDeliverService.getSurveyGroupDwzUrl(orgId, projectId, deliver.getId(), newKeyMap);
            // 创建对象时同步创建对应二维码
            String fileName = CommonUtil.fileNameFormat(node.getCode() + "@" + node.getName() + ".png");
            deliverDeliverService.createSurveyGroupQrcodes(orgId, projectId, deliver.getId(), link, fileName, false);
            DeliverDefaultDeliverStore defaultDeliver = new DeliverDefaultDeliverStore();
            defaultDeliver.setOrgId(orgId);
            defaultDeliver.setDeliverId(deliver.getId());
            defaultDeliver.setRootGroupId(rootGroupId);
            defaultDeliver.setGroupId(node.getId());
            defaultDeliver.setCode(node.getCode());
            defaultDeliver.setTitle(node.getName());
            defaultDeliver.setSurveyId(projectId);
            defaultDeliver.setStatus(status);
            defaultDeliver.setTtype(DEFAULTDELIVERSTORE_TTYPE_STORE.getNumber());
            defaultDeliver.setLink(link);
            defaultDeliver.setDisable(0);
            deliverDefaultDeliverStoreMapper.insert(defaultDeliver);
        } else {
            if (CollectionUtils.isEmpty(node.getChildrenList())) {
                return;
            }
            for (GroupNode childrenNode : node.getChildrenList()) {
                parseNode(orgId, childrenNode, /*parentNodeList, */storeLevel, keyMap, deliver, projectId, rootGroupId);
            }
        }
    }

    @Override
    public void projectDeletedShare(ProjectDeletedShareRequest request, StreamObserver<ProjectDeletedShareResponse> responseObserver) {
        ProjectDeletedShareResponse.Builder result = ProjectDeletedShareResponse.newBuilder();
        //从所拥有的项目中删除
        String surveyId = request.getSurveyId();
        List<DeliverDisturbRule> disturb_data = deliverDisturbRuleMapper.
                selectList(new LambdaQueryWrapper<DeliverDisturbRule>().in(DeliverDisturbRule::getSurveyId, request.getProjectIdsList()));
        disturb_data.forEach(data -> {
            List<String> disturbSurveyIds = JSONObject.parseArray(data.getDisturbSurveyIds(), String.class);
            if (disturbSurveyIds.contains(surveyId)) {
                disturbSurveyIds.remove(surveyId);
                DeliverDisturbRule rule = new DeliverDisturbRule();
                rule.setId(data.getId());
                rule.setDisturbSurveyIds(JSON.toJSONString(disturbSurveyIds));
                deliverDisturbRuleMapper.updateById(rule);
            }
        });
        result.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(result.build());
        responseObserver.onCompleted();
    }
}